'use strict';
const crypto = require('crypto');
module.exports = app => {
  class Controller extends app.Controller {
    async reg() {
      const { ctx, app } = this;
      // 参数验证
      ctx.validate({
        username: {
          type: 'string',
          required: true,
          range: {
            min: 5,
            max: 20
          },
          desc: '用户名'
        },
        password: {
          type: 'string',
          required: true,
          desc: '密码'
        },
        repassword: {
          type: 'string',
          required: true,
          desc: '确认密码'
        }
      }, {
        equals: [
          ['password', 'repassword']
        ]
      });
      let { username, password } = ctx.request.body;
      console.log(username, password);
      let data = await app.model.User.findOne({
        where: {
          username
        }
      })
      if (data) {
        ctx.throw(400, '用户名已存在')
      }
      let user = await app.model.User.create({
        username,
        password
      })
      if (!user) {
        ctx.throw(400, '注册失败')
      }
      ctx.apiSuccess(user)
    }
    async login() {
      const { ctx, app } = this;
      ctx.validate({
        username: {
          type: 'string',
          required: true,
          desc: '用户名'
        },
        password: {
          type: 'string',
          required: true,
          desc: '密码'
        },
      })
      let { username, password } = ctx.request.body
      console.log(username);
      let user = await app.model.User.findOne({
        where: {
          username
        }
      })
      if (!user) {
        return ctx.apiFail('当前用户不存在')
      }
      //密码验证
      this.checkpassword(password, user.password)
      user = JSON.parse(JSON.stringify(user))
      console.log(user);
      //token生成
      user.token = ctx.getToken(user)
      delete user.password;
      //加入缓存
      if (!await this.service.cache.set("user_" + user.id, user.token)) {
        ctx.throw(400, '登录失败')
      }
      ctx.apiSuccess(user)
    }
    // 退出登录
    async logout() {
      const { ctx, service } = this;
      console.log(ctx.authUser);
      // const currentUserId = ctx.authUser.id;
      // if (!await service.cache.remove('user_' + currentUserId)) {
      //   ctx.throw(400, '退出登录失败');
      // }
      ctx.apiSuccess('退出登录成功');
    }
    async getSize() {
      const { ctx, service } = this
      ctx.apiSuccess({
        total_size: ctx.authUser.total_size,
        user_size: ctx.authUser.used_size,
      })
    }
    checkpassword(password, hash_password) {
      const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
      hmac.update(password);
      if (hmac.digest('hex') !== hash_password) {
        this.ctx.throw(400, '密码错误')
      }
      return true
    }



  }
  return Controller;
};
